package com.jia.leetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: Leetcode
 * @description:  525. 连续数组  https://leetcode-cn.com/problems/contiguous-array/description/
 * @author: STU756
 * @create: 2020-08-22 13:18
 */
public class Pro0525 {
    public int findMaxLength(int[] nums) {
        int preSum = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] == 0) {
                nums[i] = -1;
            }
        }

        Map<Integer,Integer> map = new HashMap<>();
        int sum = 0;
        int ans = 0;
        for(int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if(sum == 0) {
                ans = i + 1;
            }
            if(map.containsKey(sum)) {
                ans = Math.max(ans, i - map.get(sum));
                //map.put(sum ,i);不需要覆盖，因为已经存在了，在最前面
            }else {
                map.put(sum ,i);
            }
        }
        return ans;
    }
}
